package com.qc31.monitorlib.movepoint

import com.amap.api.maps.model.LatLng
import kotlin.math.abs
import kotlin.math.atan
import kotlin.math.sqrt

/** @author joker @date 2022/7/19$ 15:07$ */
object MovePointUtil {
    // 通过设置间隔时间和距离可以控制速度和图标移动的距离
    const val TIME_INTERVAL = 10
    private const val DISTANCE = 0.00005

    //移动距离
    private var distance = DISTANCE

    fun setSpeed(progress: Int) {
        distance = progress* DISTANCE
    }

    /** 根绝两点算取图标转的角度 */
    fun getAngle(fromPoint: LatLng?, toPoint: LatLng?): Double {
        if (fromPoint == null || toPoint == null) {
            return 0.0
        }
        val slope = getSlope(fromPoint, toPoint)
        if (slope == Double.MAX_VALUE) {
            return if (toPoint.latitude > fromPoint.latitude) {
                0.0
            } else {
                180.0
            }
        }
        var deltAngle = 0f
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180f
        }
        val radio = atan(slope)
        return 180 * (radio / Math.PI) + deltAngle - 90
    }

    /**
     * 根据点和斜率算取 截距
     *
     * @param slope
     * @param point
     * @return
     */
    fun getInterception(slope: Double, point: LatLng): Double {
        return point.latitude - slope * point.longitude
    }

    /**
     * 计算斜率
     *
     * @param fromPoint
     * @param toPoint
     * @return
     */
    fun getSlope(fromPoint: LatLng, toPoint: LatLng): Double {
        return if (toPoint.longitude == fromPoint.longitude) {
            Double.MAX_VALUE
        } else (toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude)
    }

    /** 计算x方向每次移动的距离 */
    fun getXMoveDistance(slope: Double): Double {
        return if (slope == Double.MAX_VALUE || slope == 0.0) {
            distance
        } else abs(distance * 1 / slope / sqrt(1 + 1 / (slope * slope)))
    }

    /** 计算y方向每次移动的距离 */
    fun getYMoveDistance(slope: Double): Double {
        return if (slope == Double.MAX_VALUE || slope == 0.0) {
            distance
        } else abs(distance * slope / sqrt(1 + slope * slope))
    }
}